#include "NetTime.h"

const String url ="http://quan.suning.com/getSysTime.do";

NetTime ntime;

uint8_t char_to_num(char dat)
{
    return dat-0x30;
}

//解析Json信息
void get_time_json(String payload)
{
    uint8_t buf;
    uint8_t buf2;
    char *p=&payload[0];
    p+=48;
    ntime.year=char_to_num(*p++)*10;
    ntime.year+=char_to_num(*p++);
    ntime.month=char_to_num(*p++)*10;
    ntime.month+=char_to_num(*p++);
    ntime.day=char_to_num(*p++)*10;
    ntime.day+=char_to_num(*p++);
    ntime.hour=char_to_num(*p++)*10;
    ntime.hour+=char_to_num(*p++);
    ntime.min=char_to_num(*p++)*10;
    ntime.min+=char_to_num(*p++);
    ntime.second=char_to_num(*p++)*10;
    ntime.second+=char_to_num(*p++);    



    if(ntime.month<3)
    {
        buf=ntime.month+12;
        buf2 = ntime.year - 1;
    }
    else
    {
        buf=ntime.month;
        buf2 = ntime.year;
    }  
    buf ++;
    ntime.week = (buf2 + (buf2 >> 2) + (int)(26 * buf / 10) + ntime.day - 36) % 7;
    #ifdef DEBUG
    {
        Serial.printf("20%d年%d月%d日%d时%d分%d秒 星期%d\n",ntime.year,ntime.month,ntime.day,ntime.hour,ntime.min,ntime.second,ntime.week);
    }
    #endif
}

bool NetTime::get()
{
  #ifdef DEBUG
  {
    Serial.println("start get time at internet");
  }
  #endif
  String payload = http_get(url,0);
  if(strlen(&payload[0])>60)
  {
    #ifdef DEBUG
    {
        Serial.println("get success");
        Serial.print("code=");
        Serial.println(payload);
    }
    #endif
    get_time_json(payload); 
    return 1;
  }
  else
  {
    #ifdef DEBUG
    {
      Serial.println("get fail");
    }
    #endif
    return 0;
  }
}

